package com.yangzc.lion.sys.security.util;

import java.util.ArrayList;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.yangzc.lion.sys.organization.model.SysOrgPerson;
import com.yangzc.lion.sys.security.model.SecurityUser;
import com.yangzc.lion.sys.util.Commons;

/**
 * SPRING SECURITY3工具类实现类
 * 
 */
public class SecurityUtil {

	public final static String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";

	public SecurityContext getSecurityContext() {
		return (SecurityContext) Commons.ContextUtil.getSession().getAttribute(
				SPRING_SECURITY_CONTEXT);
	}

	public Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

	/**
	 * 获取SECURITY3的认证对象
	 * 
	 * @return UserDetails
	 */
	public SecurityUser getSecurityUser() {
		Object person = getAuthentication().getPrincipal();
		if (person instanceof SecurityUser) {
			return (SecurityUser) person;
		} else if (person instanceof String && person.equals("anonymous")) {
			SysOrgPerson ps = new SysOrgPerson();
			ps.setFdName("匿名用户");
			ps.setFdLoginName("anonymous");
			SecurityUser se = new SecurityUser(ps,
					new ArrayList<GrantedAuthority>());
			return se;
		}
		return null;
	}
}